/**
 * 入参typeStatus:1新增，2编辑，3查看 ；id:编辑查看 传入id
 *
 * */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Spin, message, Modal } from 'antd';
import { PrimaryC, PrimaryGhostC, SecondHeaderC } from '../../../../../../comps';
import myStyle from '../../index.less';
import FormTableC from './formTableC';
import InitFormC from './initFormC';
import RiskC from './riskC';
import uuid from 'es6-uuid';

@connect(({ portfolioOptimizationM, workStationM, loading }) => ({
  portfolioOptimizationM,
  workStationM,
  loading,
}))
@Form.create()
export default class SettingC extends PureComponent {
  state = {
    initColumns: [
      {
        //默认表头
        key: 'asset',
        title: '资产',
        isNeed: true,
      },
      {
        key: 'initWeight',
        title: '优化前权重(%)',
        isNeed: true,
      },
      {
        key: 'expectReturn',
        title: '预期收益率(%)',
        isNeed: false,
      },
      {
        key: 'weightBottom',
        title: '权重下界(%)',
        isNeed: false,
      },
      {
        key: 'weightTop',
        title: '权重上界(%)',
        isNeed: false,
      },
    ],
    riskArgs: undefined, //风险约束的查询条件
    barraConst: '1', //默认barra 所以有风险约束1  0否
  };
  UNSAFE_componentWillMount() {
    this.originData = _.cloneDeep(this.state);
  }
  componentDidMount() {
    if (this.props.typeStatus != 1) {
      //查询回填数据
      this.props.dispatch({
        type: 'portfolioOptimizationM/querySettingById',
        payload: { id: this.props.id, fromBarra: true },
        callback: (data) => {
          if (!data) return;
          this.settingDetailByID(data, 'detail'); //设置回填参数
          if (data.barraConst == '1' && data.barraData) {
            //barra风险因子回填
            let arr = data.barraData || [];
            arr.map((item) => {
              item.key = uuid(16);
              item.minNum = item.exposureBottom;
              item.maxNum = item.exposureTop;
            });
            this.riskRef?.setState({ dataSource: [...arr] });
          }
        },
      });
    }
  }

  componentWillUnmount() {
    // 离开前清除models数据
  }

  //切换列表是否下拉表格变化
  handleSelectChange = (e, type) => {
    const { initColumns } = this.state;
    if (type == 'barraConst') {
      //当选择“是”时，下方出现【风险因子约束设置】
      this.setState({
        barraConst: e,
      });
      if (e == '0')
        this.setState({
          //清空条件 否的时候
          riskArgs: undefined,
        });
      return;
    }
    initColumns.map((item) => {
      //决定是否显示该列
      if (type == 'assetConst') {
        if (item.key == 'weightBottom') {
          item.isNeed = e == '1' ? true : false;
        }
        if (item.key == 'weightTop') {
          item.isNeed = e == '1' ? true : false;
        }
      } else {
        if (item.key == type) {
          item.isNeed = e == '1' ? true : false;
        }
      }
    });
    this.setState({
      initColumns: [...initColumns],
    });
  };
  //提交 执行分析按钮
  submit = () => {
    const { dispatch, type } = this.props;
    const arr = this.child.submit();
    const values = this.initFormRef.submit();
    let barraData = {};
    if (values?.barraConst == '1') {
      //有风险因子约束
      const riskData = this.riskRef.submit();
      if (riskData == undefined) message.warning('请点击“刷新”得到最新的风格因子暴露度值');
      if (!arr || !riskData || !values) return; //校验config表单数据，及表格数据
      let arrRisk = riskData.map((item) => {
        return {
          factorName: item.factorName,
          exposureBottom: item.exposureBottom,
          exposureTop: item.exposureTop,
          exposureInit: item.exposureInit,
          factorCnName: item.factorCnName,
        };
      });
      barraData = arrRisk;
    } else if(values?.barraConst == '0'){
      if (!arr || !values) return; //校验config表单数据，及表格数据
    }
    let payload={};
    const {
      workStationM: { productTableList = [] },
    } = this.props;
    //拿到组合的name
    let productObj = productTableList.filter((item) => {
      return item.portfolioId == this.props.portfolioId;
    });

    const tempData = JSON.parse(JSON.stringify(arr.slice(0, arr.length - 1)));
    const configData = tempData.filter((item) => item.asset);
    payload = {
      id: this.props.id, //编辑时候提交
      configData: [...configData],
      ...values,
      beginDate: values.beginDate?.format('YYYY-MM-DD'),
      portfolio: this.props.portfolioId,
      portfolioName: productObj[0]?.title,
    };
    if (!values.beginDate || !values.endDate) return;
    payload.endDate = values.endDate.format('YYYY-MM-DD');
    if (payload.barraConst == '1') {
      //barra因子下 组合 基准 持仓设置有变动 必须重新点击刷新按钮获取最新的风格因子暴露度值
      payload.barraData = barraData;
    }

    dispatch({
      type: 'optimizationM/executeOptimization',
      payload: {
        ...payload,
        type: '0',
      },
      callback: (data) => {
        if (data) {
          //提交成功 页面弹窗提示
          if (data != 1) this.reset(); //没有结果的时候 可以不刷新

          Modal.info({
            content: data == 1 ? '当前参数配置下，无优化结果，请调整参数' : '优化完成，可点击【查看分析结果】进行查看',
            okText: '确定',
          });
          if (this.props.typeStatus != 1) {
            this.props.changeStatus('1', '1');
          }
        }
      },
    });
  };

  //重置reset
  reset = () => {
    this.initFormRef.reset(); //重置表单
    this.setState({ ..._.cloneDeep(this.originData) });
    this.child.reset(); //清空表格数据
    if (this.riskRef) this.riskRef.reset(); //清空风险
  };

  //settingDetailByID 回填详情数据
  settingDetailByID = (data, type) => {
    if (type == 'detail') {
      this.initFormRef.settingDetails(data); //参数回填
      //持仓表头和设置联调 权重约束
      this.handleSelectChange(`${data.assetConst}`, 'assetConst');
      this.handleSelectChange(`${data.expectReturn}`, 'expectReturn');
    }
    this.child?.setState({date:data.endDate||undefined});//回填优化前持仓日期
    let configData = [];
    var sum = 0;
    let assetData = data.assetConfigData || data.configData;
    let myData = [];
    assetData &&
      assetData.map((item, index) => {
        myData.push(_.cloneDeep(item));
        item.order = index + 1;
        configData.push(item);
        sum += item.initWeight;
      });
    configData.push({ order: '总计', initWeight: sum });
    this.child.setState({
      dataSource: [...configData],
    });
    const {
      workStationM: { productTableList = [] },
    } = this.props;
    let productObj = productTableList.filter((item) => {
      return item.portfolioId == data.portfolioId;
    });
    //存储风险因子 查询条件 持仓设置 组合 基准
    if (data.barraConst == '1' && data.barraData)
      this.setState({
        riskArgs: {
          indexcode: productObj[0]?.performanceBenchmarkId, //业绩基准
          flag: productObj[0]?.isBenchmarkFlag, //flag  枚举值为：0,1;其中1
          configData: [...myData],
        },
      });
    //通知父组件改变下拉
    this.props.changePortfolio(this.getCode(data.portfolio));
  };
  //获取组合code
  getCode = (id) => {
    const {
      workStationM: { productTableList = [] },
    } = this.props;
    let productObj = productTableList.filter((item) => item.portfolioId == id);
    return productObj[0]?.value;
  };
  //查询风险因子
  queryRisk = () => {
    const { initColumns } = this.state;
    const arr = this.child.submit();
    if (!arr) {
      //校验持仓设置的数据 是否ok
      message.destroy();
      message.warning('请完善持仓设置数据！');
      return;
    }
    const tempData = JSON.parse(JSON.stringify(arr.slice(0, arr.length - 1)));
    const configData = tempData.filter((item) => item.asset);
    const {
      workStationM: { productTableList = [] },
    } = this.props;
    let productObj = productTableList.filter((item) => {
      return item.portfolioId == this.props.portfolioId;
    });
    this.setState({
      riskArgs: {
        timeStamps: new Date().getTime(),
        indexcode: productObj[0]?.performanceBenchmarkId, //业绩基准
        flag: productObj[0]?.isBenchmarkFlag, //flag  枚举值为：0,1;其中1 表示获取表inx_componentweight 中的标准资产权重数据 ；0 表示使用系统自定义权重数据
        configData: [...configData],
      },
    });
  };
  //查询持仓配置列表
  getHoldList = (e) => {
    //持仓设置组件查询列表
    this.child?.getHoldList(e);
    //如果持仓设置列表变更，则风险因子清空
    this.riskRef.setState({
      dataSource: [],
    });
  };
  renderContent = () => {
    const { loading, typeStatus, productCode, portfolioType, portfolioId } = this.props;
    const { initColumns, barraConst } = this.state;
    return (
      <div className={myStyle.stock}>
        <Spin spinning={loading.effects['optimizationM/executeOptimization'] == true}>
          <div>
            <InitFormC
              productCode={productCode}
              portfolioType={portfolioType}
              typeStatus={typeStatus}
              onRef={(ref) => {
                this.initFormRef = ref;
              }}
              getHoldList={this.getHoldList}
              handleSelectChange={this.handleSelectChange}
            />
            <FormTableC
              typeStatus={typeStatus}
              productCode={productCode}
              portfolioType={portfolioType}
              portfolioId={portfolioId}
              barraConst={barraConst}
              initColumns={initColumns}
              onRef={(ref) => {
                this.child = ref;
              }}
            />
            {this.state.barraConst == '1' ? (
              <>
                <SecondHeaderC title='风险因子约束' topHeight={true} />
                {typeStatus != '3' && (
                  <PrimaryC style={{ marginBottom: '10px' }} onClick={this.queryRisk} title={'刷新'} helper='权重调整后，点击“刷新”得到最新的风格因子暴露度值' />
                )}
                <RiskC
                  typeStatus={typeStatus}
                  riskArgs={this.state.riskArgs}
                  onRef={(ref) => {
                    this.riskRef = ref;
                  }}
                />
              </>
            ) : null}
          </div>
        </Spin>
      </div>
    );
  };

  render() {
    const { loading, typeStatus } = this.props;
    return (
      <div>
        {this.renderContent()}

        <div style={{ width: '100%', textAlign: 'right' }}>
          {typeStatus == '1' ? (
            <div className={myStyle.footerBtn}>
              <span
                className={myStyle.mainColor}
                onClick={() => {
                  this.props.changeStatus('2');
                }}
              >
                查看分析结果
              </span>
              <PrimaryC loading={loading.effects['optimizationM/executeOptimization'] == true} title='提交' onClick={this.submit} />
              <PrimaryGhostC title='重置' onClick={this.reset} />
            </div>
          ) : null}
          {typeStatus == '2' ? (
            <PrimaryC loading={loading.effects['optimizationM/executeOptimization'] == true} style={{ marginRight: '15px' }} title='提交' onClick={this.submit} />
          ) : null}
          {typeStatus != '1' ? (
            <PrimaryGhostC
              title='取消'
              onClick={() => {
                this.props.changeStatus('2');
              }}
            />
          ) : null}
        </div>
      </div>
    );
  }
}
